
#include "stdafx.h"
#include "Googlemap.h"

GoogleMap::GoogleMap(const CString apiKey)
{
	m_szAPIKey = apiKey;
	offset= 268435456;
	radius = offset / 3.14;
}

std::vector<CString> GoogleMap::split(CString s, char sep)
{
	std::vector<CString> res;
	CString tmp = CString("");
	for(int i=0;i<s.GetLength();i++)
	{
		if(s[i]==sep) {
			if(tmp.GetLength()>0) {
				res.push_back(tmp);
				tmp = "";
			}
		} else {
			tmp = tmp + s[i];
		}
	}
	if(tmp.GetLength()>0) {
		res.push_back(tmp);
	}
	return res;
}

CString GoogleMap::getGeocodeError(int errorCode)
{
	switch(errorCode)
	{
		case 400:
			return CString("Bad request");
		case 500:
			return CString("Server error");
		case 601:
			return CString("Missing query");
		case 602:
			return CString("Unknown address");
		case 603:
			return CString("Unavailable address");
		case 604:
			return CString("Unknown directions");
		case 610:
			return CString("Bad API key");
		case 620:
			return CString("Too many queries");
		default:
			return CString("Generic error");
	}
}

CString GoogleMap::urlEncode(CString str)
{
	URLEncode encoder;
	return CString(encoder.encode(str));
}


CString GoogleMap::getGeocodeUrl(CString address)
{
	return CString("http://maps.google.com/maps/geo?q=") 
			+ urlEncode(address)
			+ CString("&output=csv&key=") + m_szAPIKey;
}

CString GoogleMap::getMapUrl(int width, int height, double lng, double lat, int zoom, CString format)
{
	char * szUrl = (char*)malloc(256*2);
	char * szFormat = "http://maps.google.com/staticmap?center=%f,%f&format=%s&zoom=%d&size=%dx%d&key=%s";
	sprintf(szUrl, szFormat, lat, lng, format, zoom, width, height, m_szAPIKey);
	CString s = CString(szUrl);

	if (0 < m_liMarkers.size()) {
		CString markers = _T("&markers=");
		std::vector<CString>::iterator ite = m_liMarkers.begin();
		while (ite != m_liMarkers.end()) {
			markers += *ite;
			ite++;
			if (ite != m_liMarkers.end())
				markers += _T("|");
		}
		markers += _T("&sensor=true_or_false");
		s += markers;
	}

	return  s;
}

BYTE* GoogleMap::loadHttpFile(CString url, long &length)
{
	BYTE* buffer = NULL;
	CInternetSession session;
	CHttpConnection * hc = NULL;
	
	hc = session.GetHttpConnection(_T("maps.google.com"), 0, 80, NULL, NULL); 
	if (!hc) return NULL;
	CHttpFile* pFile = (CHttpFile*)session.OpenURL(url);

	length = (long)pFile->GetLength();
	if (!length) return NULL;

	buffer = (BYTE*)malloc(length + 1);
	memset(buffer, 0, length +1);

	for (DWORD dwRead1;dwRead1=pFile->Read(buffer,length););
	return buffer;
}

std::vector<double> GoogleMap::geocodeAddress(CString address) 
{
	long length = 0;
	std::vector<double> result;
	BYTE* res = loadHttpFile(getGeocodeUrl(address), length);
	CString resString(reinterpret_cast<const char *>(res), length);
	std::vector<CString> data = split(resString, ',');
	if(data[0] == CString("200")) {
		int errorCode = _wtoi(data[0].GetBuffer());
		// exception
	} else {
		result.push_back(_wtoi(data[1].GetBuffer()));
		result.push_back(_wtoi(data[2].GetBuffer()));
	}
	return result;
}

CString GoogleMap::makeImgFile(const BYTE * data, long len)
{
	FILE * fp = fopen("\\map.jpg", "wb");
	if (fp) {
		fwrite(data, 1, len, fp);
		fclose(fp);
		return CString("\\map.jpg");
	} else {
		return CString("");
	}
}

void GoogleMap::addMarker(double lat, double lon)
{
	char szTemp[256];
	sprintf(szTemp, "%f,%f", lat, lon);
	m_liMarkers.push_back(CString(szTemp));
}

std::vector<CString> GoogleMap::getAddressesFromKey(CString key)
{
	std::vector<CString> li;
	return li;
}

void GoogleMap::getCoordByAddr(CString addr, double &lat, double &lng)
{
	lat = 0.0;
	lng = 0.0;
}

CString GoogleMap::getDescriptivLocationUrl(double &lat, double &lng)
{
	char * szUrl = (char*)malloc(256*2);
	char * szFormat = "http://maps.google.com/maps/geo?ll=%f,%f&sensor=false&output=csv&gl=dk&key=%s";
	sprintf(szUrl, szFormat, lat, lng, m_szAPIKey);
	CString s = CString(szUrl);
	return s;
}

CString GoogleMap::loadHttpFile(CString url)
{
	CString result;
	CInternetSession session;
	CHttpConnection * hc = NULL;
	
	hc = session.GetHttpConnection(_T("maps.google.com"), 0, 80, NULL, NULL); 
	if (!hc) return NULL;
	CHttpFile* pFile = (CHttpFile*)session.OpenURL(url);
	pFile->ReadString(result);
	return result;
}

CString GoogleMap::getKeywordUrl(double lat, double lon, CString keyword)
{
	char * szUrl = (char*)malloc(256*2);
	char * szFormat = "http://ajax.googleapis.com/ajax/services/search/local?q=%s&v=1.0&sll=%f,%f&mrt=localonly";
	sprintf(szUrl, szFormat, keyword, lat, lon);
	CString s = CString(szUrl);
	return s;
}